package nancal.mp.mvc.ops

import io.kubernetes.client.openapi.apis.CoreV1Api
import io.kubernetes.client.openapi.models.V1Namespace
import io.kubernetes.client.openapi.models.V1ObjectMeta
import nancal.mp.service.K8sBaseService
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RequestMapping("/ops/k8s/ns")
@RestController
class K8sNsController {


    @RequestMapping("/list", method = arrayOf(RequestMethod.POST, RequestMethod.GET))
    fun list(targetEnv: String): ListResult<String> {
        var api = CoreV1Api(K8sBaseService.getK8sClient(targetEnv));
        var list = api.listNamespace()
            .execute()
            .items
            .map { it.metadata!!.name!! }

        return ListResult.of(list)
    }


    @PostMapping("/add")
    fun add(targetEnv: String, name: String): JsonResult {

        var api = CoreV1Api(K8sBaseService.getK8sClient(targetEnv));
        var v1Ns = V1Namespace()
        v1Ns.kind("Namespace")
        v1Ns.apiVersion("v1")

        var v1Meta = V1ObjectMeta();
        v1Meta.name = name;
        v1Meta.putLabelsItem("name", name);
        v1Ns.metadata(v1Meta)

        var v1Namespace = api.createNamespace(v1Ns).execute()

        if (v1Namespace == null) {
            return JsonResult.error("创建失败！")
        }

        return JsonResult()
    }
}